package com.zhuimeng.guavahomework.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.taobao.tair.DataEntry;
import com.taobao.tair.Result;
import com.taobao.tair.ResultCode;
import com.taobao.tair.json.JSONObject;
import com.zhuimeng.guavahomework.component.TairManager;
import com.zhuimeng.guavahomework.dao.ResumeDao;
import com.zhuimeng.guavahomework.pojo.Resume;
import com.zhuimeng.guavahomework.pojo.ResumeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ResumeService {
    @Autowired
    ResumeDao resumeDao;
    @Autowired
    TairManager tairManager;
    Cache<Object, Object> guauaCache = CacheBuilder.newBuilder().expireAfterAccess(5,TimeUnit.SECONDS).build();
    String key= "list";

    public ResumeResult getList(){
        ResumeResult resumeResult = new ResumeResult();
        List<Resume> resumeList = null;
        resumeResult.setResumes((List<Resume>) guauaCache.getIfPresent(key));
        if (resumeResult.getResumes()!=null){
            resumeResult.setFrom("从GuauaCache读取到数据");
           return resumeResult;
        }
        Result<DataEntry> tairResult = tairManager.get(0, key);

        if (tairResult.getRc().getCode()==0){
            resumeResult.setFrom("从Tair获取到数据");
            resumeResult.setResumes((List<Resume>) tairResult.getValue().getValue());
            guauaCache.put(key,resumeResult.getResumes());
            return resumeResult;
        }
        resumeList = resumeDao.findAll();
        if (resumeList!=null && resumeList.size()>0){
            resumeResult.setResumes(resumeList);
            resumeResult.setFrom("从数据库取，并存入Tair和GuauaCache的缓存中");
            tairManager.put(0, key, (Serializable) resumeList,0,10);
            guauaCache.put(key,resumeList);
        }
        return resumeResult;
    }
}
